package com.btl.cygf;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.btl.bean.Person;
import com.btl.fragment.ShequFragment;
import com.btl.fragment.ShouyeFragment;
import com.btl.fragment.WoFragment;
import com.btl.http.HttpServies;
import com.btl.utils.MD5Encrypt;
import com.btl.utils.SavaPersonInfo;
import com.yzx.yunyanzhengdemo.activity.LoginActivity;

public class MainActivity extends FragmentActivity implements OnClickListener {

	// //----------------------------------------------------------
	// private ViewPager viewPager;// 页卡内容
	// private ImageView imageView;// 动画图片
	// private TextView voiceAnswer, healthPedia, pDected;// 选项名称
	// private List<Fragment> fragments;// Tab页面列表
	// private int offset = 0;// 动画图片偏移量
	// private int currIndex = 0;// 当前页卡编号
	// private int bmpW;// 动画图片宽度
	// private int selectedColor, unSelectedColor;
	// /** 页卡总数 **/
	// private static final int pageSize = 3;
	// //-----------------------------------------------------------

	// 用于首页的Fragment
	private ShouyeFragment shouyeFragment;
	// 用于社区的Fragment
	private ShequFragment shequFragment;
	// 用于我的Fragment
	private WoFragment woFragment;

	// 首页界面布局
	private View shouyeLayout;
	// 社区界面布局
	private View shequLayout;
	// 我界面布局
	private View woLayout;

	// 在Tab布局上显示消息图标的控件
	private ImageView shouyeImage;
	private ImageView shequImage;
	private ImageView woImage;

	// 在Tab布局上显示消息标题的控件
	private TextView shouyeText;
	private TextView shequText;
	private TextView woText;

	// 用于对Fragment进行管理
	private FragmentManager fm;

	private Person p;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (msg.what == 0x1124) {
				if(p == null) {
					
				} else {
					SavaPersonInfo.saveInfo(getApplicationContext(),p);
				}
				

			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		System.out.println(R.string.url);

		// 初始化布局元素
		initViews();
		fm = getSupportFragmentManager();
		// 第一次启动时选中第0个tab
		setTabSelection(0);
		// 登录成功跳转到tab3
		Intent it = getIntent();
		if (it != null) {
			int type = it.getIntExtra("type", 0);
			if (type == 1) {
				setTabSelection(2);
			}
		}
		SharedPreferences share = getSharedPreferences("login",
				Activity.MODE_WORLD_READABLE);
		final String id = share.getString("id", "");
		System.out.println("main : " + id);
		if (!id.equals("")) {
			final String pass = share.getString("pass", "");
			new Thread(new Runnable() {
				@Override
				public void run() {

					Map<String, String> params = new HashMap<>();
					params.put("id", id);
					params.put("pass", pass);

					try {
						p = (Person) HttpServies.SendPostRequest(
								getResources().getString(R.string.url) +"/CYGF/login.user",
								params, "utf-8", 3);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.sendEmptyMessage(0x1124);
				}
			}).start();
		}

	}

	/**
	 * 在这里获取到每个需要用到的控件的实例，并给它们设置好必要的点击事件。
	 */
	private void initViews() {

		// //-----------------------------------------------------------
		// selectedColor = getResources()
		// .getColor(R.color.tab_title_pressed_color);
		// unSelectedColor = getResources().getColor(
		// R.color.tab_title_normal_color);
		//
		// InitImageView();
		// InitTextView();
		// InitViewPager();
		//
		// //--------------------------------------------------------------

		shouyeLayout = findViewById(R.id.bottomMenu_shouyeLayout);
		shequLayout = findViewById(R.id.bottomMenu_shequLayout);
		woLayout = findViewById(R.id.bottomMenu_woLayout);
		shouyeImage = (ImageView) findViewById(R.id.bottomMenu_shouyeImage);
		shequImage = (ImageView) findViewById(R.id.bottomMenu_shequImage);
		woImage = (ImageView) findViewById(R.id.bottomMenu_woImage);
		shouyeText = (TextView) findViewById(R.id.bottomMenu_shouyeTitle);
		shequText = (TextView) findViewById(R.id.bottomMenu_shequTitle);
		woText = (TextView) findViewById(R.id.bottomMenu_woTitle);
		shouyeLayout.setOnClickListener(this);
		shequLayout.setOnClickListener(this);
		woLayout.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bottomMenu_shouyeLayout:
			// 当点击了消息tab时，选中第1个tab
			setTabSelection(0);
			break;
		case R.id.bottomMenu_shequLayout:
			// 当点击了联系人tab时，选中第2个tab
			setTabSelection(1);
			break;
		case R.id.bottomMenu_woLayout:
			// 当点击了动态tab时，选中第3个tab
			setTabSelection(2);
			break;

		default:
			break;
		}
	}

	/**
	 * 根据传入的index参数来设置选中的tab页。
	 * 
	 * @param index
	 *            每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
	 */
	private void setTabSelection(int index) {
		// 每次选中之前先清楚掉上次的选中状态
		clearSelection();
		// 开启一个Fragment事务
		FragmentTransaction transaction = fm.beginTransaction();
		// 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
		hideFragments(transaction);
		switch (index) {
		case 0:
			// 当点击了消息tab时，改变控件的图片和文字颜色
			shouyeImage.setImageResource(R.drawable.tab_shouye_selected);
			shouyeText.setTextColor(getResources().getColor(R.color.green));
			if (shouyeFragment == null) {
				// 如果MessageFragment为空，则创建一个并添加到界面上
				shouyeFragment = new ShouyeFragment();
				transaction.add(R.id.bottomMenu_content, shouyeFragment);
			} else {
				// 如果MessageFragment不为空，则直接将它显示出来
				transaction.show(shouyeFragment);
			}
			break;
		case 1:
			// 当点击了联系人tab时，改变控件的图片和文字颜色
			shequImage.setImageResource(R.drawable.tab_shequ_selected);
			shequText.setTextColor(getResources().getColor(R.color.green));
			if (shequFragment == null) {
				// 如果ContactsFragment为空，则创建一个并添加到界面上
				shequFragment = new ShequFragment();
				transaction.add(R.id.bottomMenu_content, shequFragment);
			} else {
				// 如果ContactsFragment不为空，则直接将它显示出来
				transaction.show(shequFragment);
			}
			break;
		case 2:
			// 当点击了动态tab时，改变控件的图片和文字颜色
			woImage.setImageResource(R.drawable.tab_wo_selected);
			woText.setTextColor(getResources().getColor(R.color.green));
			if (woFragment == null) {
				// 如果NewsFragment为空，则创建一个并添加到界面上
				woFragment = new WoFragment();
				transaction.add(R.id.bottomMenu_content, woFragment);
			} else {
				// 如果NewsFragment不为空，则直接将它显示出来
				transaction.show(woFragment);
			}
			break;

		}
		transaction.commit();
	}

	/**
	 * 清除掉所有的选中状态。
	 */
	private void clearSelection() {
		shouyeImage.setImageResource(R.drawable.tab_shouye_normal);
		shouyeText.setTextColor(Color.parseColor("#82858b"));
		shequImage.setImageResource(R.drawable.tab_shequ_normal);
		shequText.setTextColor(Color.parseColor("#82858b"));
		woImage.setImageResource(R.drawable.tab_wo_normal);
		woText.setTextColor(Color.parseColor("#82858b"));
	}

	/**
	 * 将所有的Fragment都置为隐藏状态。
	 * 
	 * @param transaction
	 *            用于对Fragment执行操作的事务
	 */
	private void hideFragments(FragmentTransaction transaction) {
		if (shouyeFragment != null) {
			transaction.hide(shouyeFragment);
		}
		if (shequFragment != null) {
			transaction.hide(shequFragment);
		}
		if (woFragment != null) {
			transaction.hide(woFragment);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				Builder builder = new Builder(MainActivity.this);
				builder.setTitle("提示");
				builder.setMessage("你确定要退出吗？");

				DialogInterface.OnClickListener dialog = new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						if (arg1 == DialogInterface.BUTTON_POSITIVE) {
							arg0.cancel();
						} else if (arg1 == DialogInterface.BUTTON_NEGATIVE) {
							MainActivity.this.finish();
						}
					}
				};
				builder.setPositiveButton("取消", dialog);
				builder.setNegativeButton("确定", dialog);
				AlertDialog alertDialog = builder.create();
				alertDialog.show();

			}
		}
		return false;
	}

	

}
